<?php
namespace app\admin\controller\house;

use app\admin\controller\Common;
use app\admin\model\HouseNote as NoteModel;
use app\admin\model\HouseProperty as PropertyModel;
use app\admin\library\Property;

class Note extends Common
{
    public function index()
    {
        $loginUser = $this->auth->getLoginUser();
        $house_property_id = $this->request->param('house_property_id/d', Property::getProperty($loginUser['id']));
        $properties = PropertyModel::where('admin_user_id', $loginUser['id'])->all();
        $this->assign('properties', $properties);
        $this->assign('house_property_id', $house_property_id);
        return $this->fetch();
    }

    public function query()
    {
        $loginUser = $this->auth->getLoginUser();
        $house_property_id = $this->request->param('house_property_id/d', Property::getProperty($loginUser['id']));
        $notes = NoteModel::where('a.house_property_id', $house_property_id)
        ->alias('a')
        ->join('HouseProperty b', 'a.house_property_id = b.id')
        ->field('a.*,b.name as property_name')
        ->order('a.id')
        ->select();
        return $this->returnLayui($notes);
    }

    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        $house_property_id = $this->request->param('house_property_id/d', 0);
        $data = ['house_property_id' => $house_property_id,
            'note' => ''
        ];
        if ($id) {
            if (!$data = NoteModel::get($id)) {
                $this->error('记录不存在。');
            }
        }
        $loginUser = $this->auth->getLoginUser();
        $property = PropertyModel::where('admin_user_id', $loginUser['id'])->all();
        $this->assign('property', $property);
        $this->assign('data', $data);
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function save()
    {
        $id = $this->request->post('id/d', 0);
        $data = [
            'house_property_id' => $this->request->post('house_property_id/d', 0),
            'note' => $this->request->post('note/s', '', 'trim')
        ];
        if ($id) {
            if (!$note = NoteModel::get($id)) {
                $this->error('修改失败，记录不存在');
            }
            $note->save($data);
            $this->success('修改成功');
        }
        NoteModel::create($data);
        $this->success('添加成功');
    }

    public function delete()
    {
        $id = $this->request->param('id/d', 0);
        if (!$note = NoteModel::get($id)) {
            $this->error('删除失败,记录不存在。');
        }
        $note->delete();
        $this->success('删除成功');
    }
}
